package com.wokeMy.view.channe.yibao;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.woke.method.MyApp;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.http.GlideImageLoader;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.turui.MyRealNameActivity;
import com.wokeMy.view.util.BitmapUtil;
import com.wokeMy.view.util.Util;
import com.wokeMy.view.view.SelectDialog;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import static com.wokeMy.view.turui.MyRealNameActivity.REQUEST_CODE_SELECT;

public class YbJingjianActivity extends BaseActivity implements OnClickListener {


    private android.widget.ImageView backmbjjiv;
    private android.widget.ImageView ybzmiv;
    private android.widget.LinearLayout ybzmrl;
    private android.widget.ImageView ybsfzmiv;
    private android.widget.LinearLayout ybsfzmrl;
    private android.widget.ImageView ybsffmiv;
    private android.widget.LinearLayout ybsffmrl;
    private android.widget.ImageView ybtreeiv;
    private android.widget.LinearLayout ybtreerl;
    private android.widget.Button ybbt;

    ImageView selectiv;

    ArrayList<ImageItem> images = null;
     List<String> names;

     String card_no;
    ImagePicker imagePicker;
    int position=0;
    String [] photoString=new String[4];
    String [] photoPath=new String[4];
    String user_id;
    Dialog mydialog;
    ArrayList<File> files=new ArrayList<>();

    private Handler uiHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Util.closeDialog(mydialog);
            mydialog= Util.createLoadingDialog(YbJingjianActivity.this);
//            updatePhtoe();
            ybjj();
        }
    };
    @Override
    public void setContentView() {
        setContentView(R.layout.activity_yb_jingjian);

    }

    @Override
    public void initView() {
        this.ybbt = (Button) findViewById(R.id.yb__bt);
        this.ybtreerl = (LinearLayout) findViewById(R.id.yb_tree_rl);
        this.ybtreeiv = (ImageView) findViewById(R.id.yb_tree_iv);
        this.ybsffmrl = (LinearLayout) findViewById(R.id.yb_sffm_rl);
        this.ybsffmiv = (ImageView) findViewById(R.id.yb_sffm_iv);
        this.ybsfzmrl = (LinearLayout) findViewById(R.id.yb_sfzm_rl);
        this.ybsfzmiv = (ImageView) findViewById(R.id.yb_sfzm_iv);
        this.ybzmrl = (LinearLayout) findViewById(R.id.yb_zm_rl);
        this.ybzmiv = (ImageView) findViewById(R.id.yb_zm_iv);
        this.backmbjjiv = (ImageView) findViewById(R.id.back_mbjj_iv);
    }

    @Override
    public void initData() {
      MyApp myapp= (MyApp) getApplication();
        user_id= myapp.getDatas_load().getId();
        names= new ArrayList<>();
        names.add("拍照");
        names.add("相册");
        card_no=getIntent().getStringExtra("card_no");
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);
    }
    @Override
    public void initActivity() {
        backmbjjiv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ybzmrl.setOnClickListener(this);
        ybsfzmrl.setOnClickListener(this);
        ybsffmrl.setOnClickListener(this);
        ybtreerl.setOnClickListener(this);
        ybbt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mydialog= Util.createLoadingDialog(YbJingjianActivity.this,"图片压缩中...");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < photoPath.length; i++) {
                            Log.e("易宝进件",photoPath[i]);
                            files.add(BitmapUtil.compressImage(BitmapFactory.decodeFile(photoPath[i]), "jpeg"));
                        }
                        Message sessage =new Message();
                        uiHandler.sendMessage(sessage);
                    }
                }).start();




            }
        });
    }


    @Override
    public void onClick(View v) {

        switch(v.getId())
        {

            case R.id.yb_zm_rl:

                position=0;
                break;
            case R.id.yb_sfzm_rl:
                position=1;
                break;
            case R.id.yb_sffm_rl:
                position=2;
                break;

            case R.id.yb_tree_rl:
                position=3;
                break;

            default:
                position=0;
                break;

        }
        Intent intent1 = new Intent(YbJingjianActivity.this, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    ImageItem item = images.get(0);
                    switch(position)
                    {

                        case 0:
                         imagePicker.getImageLoader().displayImage(YbJingjianActivity.this, item.path,ybzmiv, 0, 0);
                            break;
                        case 1:

                         imagePicker.getImageLoader().displayImage(YbJingjianActivity.this, item.path,ybsfzmiv, 0, 0);

                            break;
                        case 2:
                         imagePicker.getImageLoader().displayImage(YbJingjianActivity.this, item.path,ybsffmiv, 0, 0);

                            break;

                        case 3:
                         imagePicker.getImageLoader().displayImage(YbJingjianActivity.this, item.path,ybtreeiv, 0, 0);
                            break;

                        default:
                         imagePicker.getImageLoader().displayImage(YbJingjianActivity.this, item.path,ybzmiv, 0, 0);

                            break;

                    }
                    photoPath[position]=item.path;

                }
            }
        }
    }
    //易宝进件
    private void  ybjj() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",user_id);
        params.put("way",104);
        params.put("bankaccount",card_no);
        try {
            params.put("bankCardPhoto",files.get(0));
            params.put("idCardPhoto",files.get(1));
            params.put("idCardBackPhoto",files.get(2));
            params.put("personPhoto",files.get(3));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Log.e("易宝进件url", Constant.YBJJ_URL);
        Log.e("易宝进件params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.setTimeout(300000);
        ahc.post(Constant.YBJJ_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码
                if(i == 200){
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(YbSelectActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("易宝进件Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            Util.closeDialog(mydialog);
                            String info=jsonObject.getString("info");
                            if (jsonObject.get("flag").equals("success")) {
                                if (jsonObject.has("data")){
                                    String code  = jsonObject.getJSONObject("data").getJSONObject("data").getString("code");
                                    info  = jsonObject.getJSONObject("data").getJSONObject("data").getString("message");
                                    if (code.equals("0000")){
                                        tishiToast("进件成功");
                                        Intent intent=new Intent();
                                        intent.putExtra("card_no",card_no);
                                        setResult(Constant.RESPONSE_RHKJZF,intent);
                                        finish();
                                    }
                                }
                            }else {
                                if (jsonObject.has("data")){
                                    info  = jsonObject.getJSONObject("data").getJSONObject("data").getString("message");
                                }
                            }
                            tishi(info);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(mydialog);
//                Log.e("易宝进件onFailure","i"+i+"headers"+new String(bytes)+"bytes"+new String(bytes));
                throwable.printStackTrace();

            }
        });
    }
    public void updatePhtoe(){
        Log.e("updatePhtoe",""+photoPath[1]);
        OkGo.<String>post(Constant.YBJJ_URL)//
                .tag(this)//
                .cacheMode(CacheMode.NO_CACHE)//
                .cacheKey("no_cache")   //对于无缓存模式,该参数无效
                .cacheTime(5000)        //对于无缓存模式,该时间无效
                .params("user_id", user_id)//
                .params("way", 104)//
                .params("bankaccount", card_no)//
                .params("bankCardPhoto",files.get(0))
                .params("idCardPhoto",files.get(1))
                .params("idCardBackPhoto",files.get(2))
                .params("personPhoto",files.get(3))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Util.closeDialog(mydialog);
                        try {
                            JSONObject jsonObject =new JSONObject(response.body());


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Util.closeDialog(mydialog);
                        tishiToast("上传失败");
                    }
                });
    }
}
